#include "mprpcconfig.h"
#include <iostream>
#include <string.h>

//解析配置文件
void MprpcConfig::LoadConfigFile(const char *config_file)
{
    FILE *pf = fopen(config_file, "r");
    if(nullptr == pf)
    {
        std::cout << config_file << " is not exist!" << std::endl;
        exit(EXIT_FAILURE);
    }
    while(!feof(pf))
    {
        char buf[1024] = {0};
        fgets(buf, sizeof(buf), pf);

        //去掉字符串前面多余的空格
        std::string src_buf = buf;
        int idx = src_buf.find_first_not_of(' ');
        if(idx!=-1)
        {
            //说明字符串前面有空格
            src_buf = src_buf.substr(idx,src_buf.size()-idx);
        }
        // 判断注释
        if (src_buf[0] == '#' || src_buf.empty())
        {
            continue;
        }
        //去掉字符串后面多余的空格
        idx = src_buf.find_last_not_of(' ');
        if(idx!=-1)
        {
            //说明字符串后面有空格
            src_buf = src_buf.substr(0,idx+1);
        }

        //解析配置项
        idx = src_buf.find('=');
        if(idx == -1)
        {
            //配置不合法
            continue;
        }
        std::string key = src_buf.substr(0, idx);
        std::string value;
        Trim(key);
        int endidx = src_buf.find('\n', idx);
        value=src_buf.substr(idx+1, endidx-idx-1);
        Trim(value);
        m_configMap.insert({key, value});
    }
}

std::string MprpcConfig::Load(const std::string &key)
{
    auto it = m_configMap.find(key);
    if(it == m_configMap.end())
    {
        return "";
    }
    return it->second;
}

void MprpcConfig::Trim(std::string &src_buf)
{
    int idx = src_buf.find_first_not_of(' ');
    if(idx!=-1)
    {
        //说明字符串前面有空格
        src_buf = src_buf.substr(idx,src_buf.size()-idx);
    }
    idx = src_buf.find_last_not_of(' ');
    if(idx!=-1)
    {
        //说明字符串后面有空格
        src_buf = src_buf.substr(0,idx+1);
    }

}